package com.zy.springboot.interceptor;

import com.zy.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhaoyi
 * @date 2021/9/22 14:36
 */
public class TimeInterceptor implements HandlerInterceptor {

    //Interceptor 自动注入Service 需要特殊处理才能用比较麻烦
    @Autowired
    private UserService userService;

    ThreadLocal<Long> start = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Interceptor preHandle userService is " + userService);
        start.set(System.currentTimeMillis());
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        long l = System.currentTimeMillis() - start.get();
        System.out.println("完成耗时 " + l + " 毫秒");

        start.remove();
    }
}
